
package com.yuan.control;

import com.yuan.graduate.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

import java.util.HashMap;

/**
 * 声音控制类
 * 
 * @author YUAN
 */
public class SoundControl {
    private volatile static SoundControl sInstance;
    private HashMap<Integer, Integer> spMap = null;
    private SoundPool sp = null;
    private Context context = null;

    @SuppressLint("UseSparseArrays")
    private SoundControl(Context context) {
        sp = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        spMap = new HashMap<Integer, Integer>();
        spMap.put(0, sp.load(context, R.raw.checksound, 1));
        this.context = context;
    }

    public static SoundControl getInstance(Context context) {
        if (sInstance == null) {
            synchronized (SoundControl.class) {
                if (sInstance == null) {
                    sInstance = new SoundControl(context);
                }
            }
        }
        return sInstance;
    }

    public void playSounds(int sound, int number) {
        // 实例化AudioManager对象，控制声音
        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        // 当前音量
        float audioCurrentVolumn = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        // 播放
        sp.play(spMap.get(sound), // 声音资源
                audioCurrentVolumn, // 左声道
                audioCurrentVolumn, // 右声道
                1, // 优先级，0最低
                number, // 循环次数，0是不循环，-1是永远循环
                1); // 回放速度，0.5-2.0之间。1为正常速度
    }

    public void pauseSounds(int sound) {
        sp.pause(spMap.get(sound));
    }

    public void onDestroy() {
        // TODO Auto-generated method stub
        spMap.clear();
        sInstance = null;
        spMap = null;
        sp = null;
        context = null;
    }

}
